package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("images")
public class ImagesController {
    @Autowired
    ServletContext servletContext;

    @RequestMapping(method = RequestMethod.POST)
    public Map upload(MultipartFile file){
        HashMap map  = new HashMap();
        try {
            //获取指定文件夹upload的真是路径(绝对路径)
            //UploadUtil.upload(file,servletContext.getRealPath("/upload"));
            String realPath = servletContext.getRealPath("/upload");
            //获取图片的路径/upload/xxxxx.jpg
            String imgUrl = UploadUtil.upload(file, realPath);
            map.put("status",1);
            map.put("url",imgUrl);
        }catch (Exception e){
            e.printStackTrace();
            map.put("status",0);
            map.put("msg",e.getMessage());
        }

        //返回新生成的图片url
        return map;
    }

}
